package cn.edu.sxw.web.server.service;

import cn.edu.sxw.web.server.bean.User;
import cn.edu.sxw.web.server.utils.PasswordEncoder;

import java.sql.*;

/**
 * 账号服务
 */
public class AccountService {
    public User loginValidate(String login, String password){
        User user=this.getUserByLogin(login);
        if(user!=null){
            //对用户提交的密码进行加密
            String passwordEncrypt=PasswordEncoder.encode(password);
            //比较密文
            if(passwordEncrypt.equals(user.getPassword())){
                //登录成功返回User对象
                return user;
            }
        }
        //登录不成功返回null
        return null;
    }

    /**
     *
     * @param login
     * @return
     */
    public User getUserByLogin(String login){
        //定义查询用户的sql
        String sql="select id,login,username,password,gender,birthday,avatar,status from user_account where login=? and status=1";
        Connection connection=null;
        PreparedStatement statement=null;
        ResultSet rs=null;
        User user=null;
        try {
            //创建msyql连接
            connection=getMysqlConnection();
            //准备语句
            statement=connection.prepareStatement(sql);
            //拼装参数
            statement.setObject(1,login);
            //获得执行结果
            rs=statement.executeQuery();

            while (rs.next()){//读取查询结果并解析到User对象中
                user=new User();
                user.setAvatar(rs.getString("avatar"));
                user.setLogin(rs.getString("login"));
                user.setStatus(rs.getString("status"));
                user.setGender(rs.getString("gender"));
                user.setPassword(rs.getString("password"));
                user.setBirthday(rs.getString("birthday"));
                //只读取第一条数据
                break;
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            try {
                rs.close();
                statement.close();
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return user;
    }

    private Connection getMysqlConnection(){
        String jdbc_string="jdbc:mysql://localhost:3306/web-lesson4-server?useUnicode=true&characterEncoding=utf8";
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection connection= DriverManager.getConnection(jdbc_string,"***","***");
            System.out.println("数据库连接建立成功");
            return connection;
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("数据库连接失败："+e.getMessage());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
}
